/*
 *  Copyright 2008 The MITRE Corporation (http://www.mitre.org/). All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mitre.mrald.analysis;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;

import org.mitre.mrald.control.AbstractStep;
import org.mitre.mrald.control.MsgObject;
import org.mitre.mrald.control.WorkflowStepException;

public abstract class AnalysisManager extends AbstractStep
{
    protected MsgObject msg;
	protected ArrayList<AnalysisElement> sortedElements;
	protected String[] templateEntries;
	protected String dataFile;
	protected String templateFile;

    public AnalysisManager() {}

    public void execute( MsgObject msgObject )
        throws WorkflowStepException
    {
		try
		{
			msg = msgObject;
			dataFile = ( msgObject.getValue( "dataFile" ) )[0];
			if ( dataFile == null || dataFile.equals( null ) )
				throw new WorkflowStepException( "No data file provided so no analysis can be performed" );

			orderElements( msg );
			templateFile = makeTemplateFile();
			performAnalysis( templateFile, dataFile );
			prepareHeaders( msg );
			displayResults();
            msg.closeOut();
		}
		catch ( AnalysisManagerException ame )
		{
			throw new WorkflowStepException( ame.getMessage() );
		}
	}

    protected abstract void prepareHeaders( MsgObject msg ) throws AnalysisManagerException;

    protected abstract String makeTemplateFile() throws AnalysisManagerException;

    protected abstract void performAnalysis( String template_file, String data_file ) throws AnalysisManagerException;

    protected abstract void displayResults() throws AnalysisManagerException;

    private void orderElements( MsgObject msgObject )
    {
		ArrayList currentElements = msgObject.getWorkingObjects();
		sortedElements = new ArrayList<AnalysisElement>();
		TreeMap<Integer,AnalysisElement> orderedTree = new TreeMap<Integer,AnalysisElement>();

		AnalysisElement current_ae = null;

		for ( int i = 0; i < currentElements.size(); i++ )
		{
			current_ae = ( AnalysisElement ) currentElements.get( i );
			Integer sortedNum = new Integer( current_ae.getOrder() );
			orderedTree.put( sortedNum, current_ae );
		}

		Collection<AnalysisElement> sortedValues = orderedTree.values();
		for ( Iterator<AnalysisElement> it = sortedValues.iterator(); it.hasNext();  )
		{
			sortedElements.add( it.next() );
		}
    }
}

